import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Space, Typography, Badge, App } from 'antd';
import type { MenuProps } from 'antd';
import {
    UserOutlined,
    TeamOutlined,
    SettingOutlined,
    LogoutOutlined,
    BarChartOutlined,
    SecurityScanOutlined,
    DownOutlined,
    CrownOutlined
} from '@ant-design/icons';
import { useNavigate, Link, Outlet, useLocation } from 'react-router-dom';
import axios from 'axios';
import { AdminStatsProvider, useAdminStats } from '../contexts/AdminStatsContext';
import { WebSocketProvider } from '../contexts/WebSocketContext';
import { getFullMediaUrl } from '../utils/config';

const { Header, Sider, Content } = Layout;
const { Title } = Typography;

// 内部组件，使用Context
const AdminDashboardContent: React.FC = () => {
    const { notification } = App.useApp();
    const navigate = useNavigate();
    const location = useLocation();
    const [collapsed, setCollapsed] = useState(false);
    const [adminInfo, setAdminInfo] = useState<any>(null);
    const [adminWelcomeShown, setAdminWelcomeShown] = useState(false);

    // 使用全局统计数据Context
    const { stats: userStats, refreshStats } = useAdminStats();

    // 加载管理员信息和显示欢迎信息
    useEffect(() => {
        const loadAdminInfo = async () => {
            const token = localStorage.getItem('adminAuthToken');
            if (!token) return;

            try {
                const response = await axios.get('/api/auth/user/', {
                    headers: { 'Authorization': `Token ${token}` }
                });
                setAdminInfo(response.data);
            } catch (error) {
                console.error('Failed to load admin info:', error);
            }
        };

        // 检查是否有管理员欢迎信息需要显示（只显示一次）
        const adminWelcomeMessage = localStorage.getItem('adminWelcomeMessage');
        console.log('AdminDashboard: 检查管理员欢迎信息:', adminWelcomeMessage);
        if (adminWelcomeMessage && !adminWelcomeShown) {
            console.log('AdminDashboard: 准备显示管理员欢迎信息');
            setAdminWelcomeShown(true);
            // 立即清除localStorage，防止重复显示
            localStorage.removeItem('adminWelcomeMessage');

            // 延迟显示欢迎信息，确保页面已加载
            setTimeout(() => {
                console.log('AdminDashboard: 显示管理员欢迎通知');
                notification.success({
                    message: '管理员登录成功！',
                    description: adminWelcomeMessage,
                    duration: 4,
                    placement: 'topRight',
                    icon: <CrownOutlined style={{ color: '#faad14' }} />,
                });
                console.log('AdminDashboard: 管理员欢迎通知已显示');
            }, 500);
        } else {
            console.log('AdminDashboard: 没有找到管理员欢迎信息或已经显示过');
        }

        loadAdminInfo();
    }, []);

    // 监听管理员个人资料更新事件
    useEffect(() => {
        const handleAdminProfileUpdate = (event: any) => {
            console.log('AdminDashboard received admin profile update event:', event.detail);
            if (event.detail?.displayName) {
                console.log('Updating admin display name to:', event.detail.displayName);
                setAdminInfo((prev: any) => prev ? { ...prev, username: event.detail.displayName } : prev);
            }
            if (event.detail?.avatarUrl) {
                console.log('Updating admin avatar URL to:', event.detail.avatarUrl);
                setAdminInfo((prev: any) => prev ? {
                    ...prev,
                    profile: { ...prev.profile, avatar: event.detail.avatarUrl }
                } : prev);
            }
        };

        window.addEventListener('adminProfileUpdated', handleAdminProfileUpdate);

        return () => {
            window.removeEventListener('adminProfileUpdated', handleAdminProfileUpdate);
        };
    }, []);

    // 加载用户统计信息
    useEffect(() => {
        // 初始加载统计数据
        refreshStats();

        // 每30秒自动刷新统计信息
        const interval = setInterval(refreshStats, 30000);

        return () => clearInterval(interval);
    }, [refreshStats]);

    const handleLogout = () => {
        localStorage.removeItem('adminAuthToken');
        navigate('/admin/login');
    };

    // 侧边栏菜单项
    const menuItems: MenuProps['items'] = [
        {
            key: 'personal-group',
            label: '个人账户',
            type: 'group',
            children: [
                {
                    key: '/admin/account',
                    icon: <UserOutlined />,
                    label: <Link to="/admin/account">个人资料与设置</Link>,
                },
            ],
        },
        {
            type: 'divider',
        },
        {
            key: 'system-group',
            label: '系统管理',
            type: 'group',
            children: [
                {
                    key: '/admin/users',
                    icon: <TeamOutlined />,
                    label: <Link to="/admin/users">用户管理</Link>,
                },
                {
                    key: '/admin/devices',
                    icon: <SecurityScanOutlined />,
                    label: <Link to="/admin/devices">设备与监控</Link>,
                },
                {
                    key: '/admin/logs',
                    icon: <BarChartOutlined />,
                    label: <Link to="/admin/logs">访问日志</Link>,
                },
                {
                    key: '/admin/settings',
                    icon: <SettingOutlined />,
                    label: <Link to="/admin/settings">系统设置</Link>,
                },
            ],
        },
    ];



    return (
        <Layout style={{ minHeight: '100vh' }}>
            {/* 侧边栏 */}
            <Sider
                collapsible
                collapsed={collapsed}
                onCollapse={setCollapsed}
                theme="dark"
                width={250}
            >
                <div style={{
                    height: 64,
                    margin: 16,
                    background: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: 6,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: 'white',
                    fontWeight: 'bold',
                    overflow: 'hidden',
                    position: 'relative',
                    transition: 'all 0.2s',
                }}>
                    <span style={{
                        opacity: collapsed ? 1 : 0,
                        transition: 'opacity 0.2s',
                        position: 'absolute',
                    }}>
                        <CrownOutlined style={{ fontSize: 24 }} />
                    </span>
                    <span style={{
                        opacity: collapsed ? 0 : 1,
                        transition: 'opacity 0.2s',
                        fontSize: 16,
                    }}>
                        智能门禁管理系统
                    </span>
                </div>

                <Menu
                    theme="dark"
                    selectedKeys={[location.pathname]}
                    mode="inline"
                    items={menuItems}
                />
            </Sider>

            <Layout>
                {/* 顶部导航栏 */}
                <Header style={{
                    padding: '0 24px',
                    background: '#fff',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    boxShadow: '0 1px 4px rgba(0,21,41,.08)'
                }}>
                    <Title level={4} style={{ margin: 0, color: '#1890ff' }}>
                        管理员控制台
                    </Title>

                    <Space size="large">
                        {/* 统计信息快速显示 */}
                        {userStats && (
                            <Space size="middle">
                                <Badge count={userStats.user_counts?.total || 0} showZero>
                                    <TeamOutlined style={{ fontSize: 18, color: '#1890ff' }} />
                                </Badge>
                                <span style={{ fontSize: 12, color: '#666' }}>总用户</span>
                            </Space>
                        )}

                        {/* 管理员信息 */}
                        <Dropdown menu={{ items: [
                            {
                                key: 'logout',
                                icon: <LogoutOutlined />,
                                label: '退出登录',
                                onClick: handleLogout,
                            },
                        ]}} trigger={['click']}>
                            <Space style={{ cursor: 'pointer' }}>
                                <Avatar
                                    src={getFullMediaUrl(adminInfo?.profile?.avatar)}
                                    icon={!adminInfo?.profile?.avatar ? <UserOutlined /> : undefined}
                                />
                                <span>{adminInfo?.username || '管理员'}</span>
                                <DownOutlined />
                            </Space>
                        </Dropdown>
                    </Space>
                </Header>

                {/* 主内容区域 */}
                <Content style={{
                    margin: '24px 24px 0',
                    overflow: 'initial',
                    minHeight: 'calc(100vh - 112px)'
                }}>
                    <Outlet />
                </Content>
            </Layout>
        </Layout>
    );
};

// 主组件，提供Context
const AdminDashboard: React.FC = () => {
    const { message } = App.useApp();
    return (
        <AdminStatsProvider>
            <WebSocketProvider messageApi={message}>
                <AdminDashboardContent />
            </WebSocketProvider>
        </AdminStatsProvider>
    );
};

export default AdminDashboard;